/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

// import { Alert, Button } from 'antd';
import { pickedFaceData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import ReverseIconWidget from '@app-cad/common/RJSFWidgets/ReverseIconWidget';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useEffect, useState } from 'react';
import { ctx2 } from '../../../../../module';
import { usePlaneContext } from './PlaneContext';
import { ChildPlaneCommandProps } from './types';

type FormData = {
  plane?: pickedFaceData;
  offset: number;
  reverseDir?: boolean;
};

type Params = {
  mode: 'translate';
  plane: string;
  offset: number;
  reverseDir?: boolean;
};

export const PlaneOffset = ({
  props,
  onClose,
  editDxid,
  readonly,
}: ChildPlaneCommandProps) => {
  const initData = {
    plane: null,
    offset: 60,
  };
  const [formData, setFormData] = useState<FormData>(initData);
  const { sharedPlane, setSharedPlane } = usePlaneContext();

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params = props.params as Params;

    await initEditDependency([params.plane]);

    const plane = picker.generatePickObjByPickID(
      params.plane,
    ) as pickedFaceData;

    setFormData({
      plane,
      offset: params.offset,
      reverseDir: params.reverseDir,
    });

    setSharedPlane(plane);
  }, [editDxid]);

  useEffect(() => {
    if (sharedPlane && !formData.plane) {
      setFormData((prev) => ({ ...prev, plane: sharedPlane }));
    }
  }, [sharedPlane]);

  const isFormDataValid = () => {
    const { plane, offset } = formData;

    return plane != null && offset !== null;
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);

    ctx2.viewer.requestRender();
  };

  useEffect(() => {
    preview();
  }, [formData]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const {
    initEditDependency,
    initingEdit,
    clear,
    confirmCommand,
    isLoading,
    isPreviewLoading,
  } = useCommand('cmd-plane-offset', {
    commandName: 'CreatePlane',
    editDxid,
    onClose,
    finishDraw: checkAndFinishDraw,
  });

  const execute = (preview: boolean) => {
    const { plane, offset, reverseDir } = formData;

    return confirmCommand(
      {
        a: {
          mode: 'translate',
          plane: plane.meshId,
          offset,
          reverseDir,
        },
      },
      preview,
    );
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      plane: {
        type: 'string',
        format: PickInputRJSFFormat.PickPlane,
      },
      offset: {
        type: 'number',
        title: '偏移',
        format: NumberInputFormat.Length,
      },
      reverseDir: {
        type: 'boolean',
        title: '反向',
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      onCancel={onClose}
      submitLoading={isLoading || isPreviewLoading}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        if (v.plane && v.plane !== formData.plane) {
          setSharedPlane(v.plane);
        }

        setFormData(v);
      }}
      widgets={{
        reverseIcon: ReverseIconWidget,
      }}
      extraUiSchema={{
        plane: {
          'ui:placeholder': '请输入平面',
          'ui:autofocus': true,
          'ui:disabled': readonly,
        },
        offset: {
          'ui:placeholder': '请输入偏移值',
          'ui:disabled': readonly,
        },
        reverseDir: {
          'ui:classNames': 'plane-offset-form-reverse-direction',
          'ui:widget': 'reverseIcon',
          'ui:label': false,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
};
